import traceback

import yaml

from conf.setting import FILE_PATH
import os
from common.recordlog import logs
from conf.openrationConfig import OperationConfig

def get_testcase_yaml(file):
    """
    获取yaml文件的数据
    :param file: yaml文件的路径
    :return: yaml文件内容
    """
    testcase_list = []
    try:
        with open(file, 'r', encoding='utf-8') as f:
            data = yaml.safe_load(f)
            if len(data) <= 1:
                yaml_data = data[0]
                base_info = yaml_data.get('baseInfo')
                for ts in yaml_data.get('testCase'):
                    param = [base_info, ts]
                    testcase_list.append(param)
                return testcase_list
            else:
                return data

    except UnicodeDecodeError:
        logs.error(
            f"[{file}]文件编码格式错误，--尝试使用utf-8编码解码YAML文件时发生了错误，请确保你的yaml文件是UTF-8格式！")
    except FileNotFoundError:
        logs.error(f'[{file}]文件未找到，请检查路径是否正确')
    except Exception as e:
        logs.error(f'获取【{file}】文件数据时出现未知错误: {str(e)}')


class ReadYamlData(object):
    def __init__(self, yaml_file=None):
        if yaml_file is not None:
            self.yaml_file = yaml_file
        else:
            pass
        self.conf = OperationConfig()
        self.yaml_data = None

    def write_yaml_data(self, value):
        """
        写入数据到yaml文件
        :param value: (dict)类型
        :return:
        """
        file_path = FILE_PATH['extract']
        if not os.path.exists(file_path):
            os.system(file_path)
        try:
            with open(file_path, 'a', encoding='utf-8') as f:
                if isinstance(value, dict):
                    yaml.dump(value, f, allow_unicode=True)
                else:
                    logs.error('写入[extract,yaml]的数据必须为dict格式')
        except Exception as e:
            logs.error(str(traceback.format_exc()))


    def get_extract_yaml(self, key, *sub_keys):
        """
        读取接口提取的变量值，支持多层嵌套 key
        :param key: 主 key 值
        :param sub_keys: 子 key 值（可变参数）
        :return: 提取的最终数据
        """
        current_data=None
        if not os.path.exists(FILE_PATH['extract']):
            os.system(FILE_PATH['extract'])
            logs.info(f"[{FILE_PATH['extract.yaml']}]文件不存在，已自动创建")
        # 读取数据
        # 获取主 key 数据
        try:
            with open(FILE_PATH['extract'], 'r', encoding='utf-8') as f:
                data = yaml.safe_load(f)
            try:
                current_data = data[key]
            except KeyError:
                logs.error(f'[{FILE_PATH["extract.yaml"]}]文件中不存在【{key}】主 key 值')
        # 遍历 sub_keys 进行嵌套访问
            for sub_key in sub_keys:
                try:
                    current_data = current_data[sub_key]
                except KeyError:
                    logs.error(f'[{FILE_PATH["extract.yaml"]}]文件中不存在【{sub_key}】次 key 值')
            return current_data
        except Exception as e:
            logs.error(f'获取【{FILE_PATH["extract.yaml"]}】文件数据时出现未知错误: {str(e)}')


    def clear_yaml_data(self):
        """清空extract.yaml文件数据"""
        with open(FILE_PATH['extract'], 'w', encoding='utf-8') as f:
            f.truncate()


    def get_yaml_data(self):
        try:
            with open(self.yaml_data,'r',encoding='utf-8') as f:
                self.yaml_data = yaml.safe_load(f)
                return self.yaml_data
        except Exception as e:
            logs.error(f'获取【{self.yaml_data}】文件数据时出现未知错误: {str(e)}')

